package com.utc.cards.player.jade.agent.playerAgent;

import jade.core.AID;
import jade.core.behaviours.Behaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.utc.cards.Constants;
import com.utc.cards.common.jade.Mapper;
import com.utc.cards.model.card.Card;
import com.utc.cards.model.deck.Deck;
import com.utc.cards.model.game.Info;
import com.utc.cards.model.game.InfoType;

public class AskAdviceBehaviour extends Behaviour
{

    private static final long serialVersionUID = -4110378700750830452L;
    private static Logger log = LoggerFactory.getLogger(AskAdviceBehaviour.class);
    private boolean done = false;
    private PlayerAgent agent;

    // le behaviour de demande d'aide envoie la demande dans son
    // constructeur et attend une liste de cartes dans la réponse de la
    // boucle action(), on fait ensuite jouer au hasard une des cartes recu
    // dans ce seul behaviour
    public AskAdviceBehaviour(PlayerAgent playerAgent)
    {
        this.agent = playerAgent;
    }

    @Override
    public void onStart()
    {
        log.debug("Asking advice ...");
        ACLMessage message = new ACLMessage(ACLMessage.INFORM);
        message.setConversationId("info");
        message.addReceiver(new AID(Constants.CARDS_HOST_RULES_AGENT_NAME, AID.ISLOCALNAME));
        Info info = new Info(InfoType.ASK_ADVICE, null);
        try
        {
            message.setContent(Mapper.getObjectMapper().writeValueAsString(info));
            agent.send(message);
            log.debug("Asking advice : ask sent ...");
        }
        catch (JsonProcessingException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void action()
    {
        MessageTemplate pattern = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM), MessageTemplate.MatchConversationId("advice"));
        ACLMessage message = agent.receive(pattern);
        if (message != null)
        {
            log.debug("Asking advice : receiving cards...");
            try
            {
                Deck deck = Mapper.getObjectMapper().readValue(message.getContent(), Deck.class);
                Card card = deck.get(0);
                log.debug("Asking advice : agent.onAdvice()");
                agent.onAdvice(card);
                done = true;
                log.debug("Asking advice : DONE");
            }
            catch (Exception e)
            {
                log.error("Error while mapping String to Deck");
                e.printStackTrace();
                done = true;
            }
        }
        block();
    }

    @Override
    public boolean done()
    {
        return done;
    }

}
